package com.offroader.http;

import java.io.File;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.apache.http.Header;

import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.offroader.utils.FileUtils;
import com.offroader.utils.JsonUtils;

public class MyJsonHttpResponseHandler<Caller, T> extends BaseJsonHttpResponseHandler<T> {
	private boolean isTest;
	protected Class<T> clazz;
	protected Caller caller;
	
	public MyJsonHttpResponseHandler() {

		//获得泛型类型
		doGetClass();

	}
	
//	public MyJsonHttpResponseHandler(Caller caller) {
//		this.caller = caller;
//
//		//获得泛型类型
//		doGetClass();
//
//	}

	public void init(Caller caller){
		this.caller = caller;
	}

	@Override
	public void onStart() {
		// called before request is started
	}

	@Override
	public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonResponse, T page) {
		// called when response HTTP status is "4XX" (eg. 401, 403, 404)

	}

	@Override
	public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, T page) {
		// called when response HTTP status is "200 OK"
	}

	@Override
	public void onRetry(int retryNo) {
		// called when request is retried
	}

	@Override
	protected T parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
		// Should return deserialized instance of generic type, may return object for more vague handling
		if (isTest) {
			//模拟接口返回数据
			String path = "test" + File.separator;
			String fileName = clazz.getSimpleName();
			String extName = ".txt";
			String json = FileUtils.getFromAssets(path + fileName + extName);
			rawJsonData = json;
//			LogUtils.info("@@@@返回测试数据|"+rawJsonData);
			return JsonUtils.fromJson(rawJsonData, clazz);

		} else {

			if (isFailure)
				return null;

			return JsonUtils.fromJson(rawJsonData, clazz);

		}

	}

	public void setTest(boolean isTest) {
		this.isTest = isTest;
	}

	private void doGetClass() {
		Type genType = getClass().getGenericSuperclass();
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		clazz = (Class<T>) params[params.length - 1];
	}

}
